package com.tencent.xinyapayface.facePay;

import android.content.Context;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.xinyapayface.Contants;
import com.tencent.wxpayface.IWxPayfaceCallback;
import com.tencent.wxpayface.WxPayFace;
import com.tencent.wxpayface.WxfacePayCommonCode;
import com.tencent.xinyapayface.finalValue.FaceFinaleValue;
import com.tencent.xinyapayface.gson.GsonUtils;
import com.tencent.xinyapayface.util.AppInstalledUtil;
import com.tencent.xinyapayface.util.LogUtil;
import com.tencent.xinyapayface.util.UpgradeUtils;

import java.util.HashMap;
import java.util.Map;

import xinya.com.xinyapayment.lib.PayMentCtr;
import xinya.com.xinyapayment.lib.bean.Order;
import xinya.com.xinyapayment.lib.interfaceBag.OnOrderResponListener;

/**
 * Created by zhangjiebo on 2019/9/4.
 *
 * @author ZhangJieBo
 */
public class FacePayCtr {
    private static final String PARAMS_FACE_AUTHTYPE = "face_authtype";
    private static final String PARAMS_APPID = "appid";
    private static final String PARAMS_SUB_APPID = "sub_appid";
    private static final String PARAMS_MCH_ID = "mch_id";
    private static final String PARAMS_MCH_NAME = "mch_name";
    private static final String PARAMS_SUB_MCH_ID = "sub_mch_id";
    private static final String PARAMS_STORE_ID = "store_id";
    private static final String PARAMS_AUTHINFO = "authinfo";
    private static final String PARAMS_OUT_TRADE_NO = "out_trade_no";
    private static final String PARAMS_TOTAL_FEE = "total_fee";
    private static final String PARAMS_TELEPHONE = "telephone";
    Context context;
    private String appid, mch_id, store_id, trade_no, sub_mch_id, sub_appid, subject, goods_list, notify_url, md5Key, merchant_sn, platform_sn;
    int total_fee;
    long cashier_id;
    private String host = "http://paytest.xinyartech.com";
    private UpgradeUtils upgradeUtils;

    public interface OnInitResultListener{
        void success();
        void fail();
    }

    OnInitResultListener onInitResultListener;

    public interface OnResultListener {
        /**
         * 支付成功
         */
        void success(String order_no);

        /**
         * 发生错误
         */
        void error(String msg);
    }

    private OnResultListener onResultListener;

    public void setOnResultListener(OnResultListener onResultListener) {
        this.onResultListener = onResultListener;
    }

    public FacePayCtr(Context context) {
        this.context = context;
    }

    /**
     * 人脸支付初始化，在application中执行一次就行
     *
     * @param merchant_sn 商户号
     * @param platform_sn 代理商编号
     * @param md5Key      md5Key加密
     */
    public void init(String merchant_sn, String platform_sn, String md5Key,OnInitResultListener onInitResultListener) {
        this.onInitResultListener = onInitResultListener;
        this.md5Key = md5Key;
        this.merchant_sn = merchant_sn;
        this.platform_sn = platform_sn;
        initPayFace();
    }

    /**
     * 设置支付请求地址
     * @param host
     */
    public void setHost(String host){
        new PayMentCtr(context).setHost(host);//可选
    }

    /**
     * 是否是测试
     *
     * @param isTest
     */
    public void setIsTest(boolean isTest) {
        new PayMentCtr(context).setIsTest(isTest);
    }

    private void initPayFace() {
        LogUtil.LogShitou("FacePayCtr--initPayFace", "0000000000");
        new PayMentCtr(context).setMerchant_sn(merchant_sn, md5Key);
        new PayMentCtr(context).setPlatform_sn(platform_sn, md5Key);
        WxPayFace.getInstance().initWxpayface(context, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) {
                LogUtil.LogShitou("FacePayCtr--response", "11111111111111");
                String code = (String) info.get(FaceFinaleValue.RETURN_CODE);
                if (code == null || !code.equals(WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS)) {
                    onInitResultListener.fail();
                }else {
                    onInitResultListener.success();
                    Contants.mHasInited = true;
                }
            }
        });
    }

    /**
     * 释放人脸支付资源，在使用到的acticity的ondestory中使用
     */
    public void releasePayFace() {
        WxPayFace.getInstance().releaseWxpayface(context);
    }

    /**
     * 人脸支付
     *
     * @param store_id       店铺id，自定义，自传
     * @param cashier_id     收银员id
     * @param amount         订单金额，单位分
     * @param local_order_no 商户本地订单号(如果非空请确保唯一)
     * @param subject        订单描述（为空时系统将自动生成描述）
     * @param goods_list     商品列表（json串）单条商品包含字段product_id=商品编号，product=商品名称，num=商品数量，amount=商品金额，remark=商品备注
     * @param notify_url     回调地址(订单支付成功时回调通知支付结果，通知次数8次)
     */
    public void pay(String store_id, long cashier_id, int amount, String local_order_no, String subject, String goods_list, String notify_url) {
        this.store_id = store_id;
        this.trade_no = local_order_no;
        this.total_fee = amount;
        this.cashier_id = cashier_id;
        this.subject = subject;
        this.goods_list = goods_list;
        this.notify_url = notify_url;
        getRawData();
    }

    /**
     * 检查是否安装微信刷脸支付app
     */
    public boolean checkAppExit() {
        if (!AppInstalledUtil.isAppInstalled(context, "com.tencent.wxpayface")) {
//            Toast.makeText(context, "刷脸支付app未安装", Toast.LENGTH_SHORT).show();
//            Log.e("WxPayFace", "刷脸支付app未安装");
            return false;
        } else {
            return true;
        }
    }

    public void checkDownloadUrlRight(UpgradeUtils.CheckUpgradeListener checkUpgradeListener){
        upgradeUtils = new UpgradeUtils(context);
        upgradeUtils.checkUpgrade(Contants.faceAppDownLoadUrl, checkUpgradeListener);
    }

    /**
     * 下载刷脸APk
     */
    public void downloadFacePayApk(){
        if (upgradeUtils==null){
            throw new RuntimeException("请先执行checkDownloadUrlRight方法");
        }
        upgradeUtils.downLoadApk();
    }

    /**
     * 获取人脸验证信息。
     * 作用：获取到验证信息后，才可调用获取人识别。
     */
    private void getRawData() {
        if (!AppInstalledUtil.isAppInstalled(context, "com.tencent.wxpayface")) {
            Toast.makeText(context, "刷脸支付app未安装", Toast.LENGTH_SHORT).show();
            Log.e("WxPayFace", "刷脸支付app未安装");
            return;
        }
        if (!Contants.mHasInited) {
            Toast.makeText(context, "人脸支付初始化中", Toast.LENGTH_SHORT).show();
            initPayFace();
            return;
        }
        WxPayFace.getInstance().getWxpayfaceRawdata(new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                String code = (String) info.get(FaceFinaleValue.RETURN_CODE);
                if (code == null || !code.equals(WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS)) {
                    throw new RemoteException("获取rawdata失败");
                }
                String mRawData = info.get("rawdata").toString();
                if (mRawData == null) {
                    throw new RemoteException("rawdata为空");
                }
//                try {
                LogUtil.LogShitou("IFSFactoryTestActivity--response mRawData", "" + mRawData);
                getAuthInfo(mRawData);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    throw new RemoteException("authinfo获取出错");
//                }
            }
        });
    }

    /**
     * 获取调用凭证
     *
     * @param rawdata
     */
    private void getAuthInfo(String rawdata) {

        new PayMentCtr(context).orderWxFace1(cashier_id, total_fee, trade_no, subject, goods_list, notify_url, rawdata, new OnOrderResponListener() {
            @Override
            public void success(Order order) {
                String mAuthInfo = order.getAuthinfo();
                if (TextUtils.isEmpty(mAuthInfo)) {
                    onResultListener.error("authinfo为空");
                    return;
                }
                doPay(order);
            }

            @Override
            public void fail(String msg) {
                Log.e("报错了》》",msg);
                onResultListener.error(msg);
            }
        });
    }


    /**
     * 开始支付
     *
     * @return
     */
    private boolean doPay(final Order order) {
        HashMap params = new HashMap();
//        params.put(PARAMS_FACE_AUTHTYPE, "FACEID-ONCE");
        params.put(PARAMS_FACE_AUTHTYPE, "FACEPAY");
        params.put(PARAMS_APPID, order.getAppid());
        params.put(PARAMS_MCH_ID, order.getMch_id());
        params.put(PARAMS_SUB_APPID, order.getSub_appid());
        params.put(PARAMS_SUB_MCH_ID, order.getSub_mch_id());
        params.put(PARAMS_STORE_ID, store_id);
        params.put(PARAMS_OUT_TRADE_NO, order.getOrder_no());
        params.put(PARAMS_TOTAL_FEE, String.valueOf(total_fee));
        params.put(PARAMS_TELEPHONE, "");
        params.put(PARAMS_AUTHINFO, order.getAuthinfo());
        LogUtil.LogShitou("FacePayCtr--doPay", "total_fee "+total_fee);
        WxPayFace.getInstance().getWxpayfaceCode(params, new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                LogUtil.LogShitou("FacePayCtr--response", "" + GsonUtils.parseObject(info));
                new PayMentCtr(context).orderWxFace2(order.getOrder_no(), (String) info.get("openid"), (String) info.get("face_code"), new OnOrderResponListener() {
                    @Override
                    public void success(Order order) {
                        onResultListener.success(order.getOrder_no());
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(2000);
                                } catch (Exception e) {
                                }
                                WxPayFace.getInstance().updateWxpayfacePayResult(new HashMap(), new IWxPayfaceCallback() {
                                    @Override
                                    public void response(Map info) throws RemoteException {
                                        LogUtil.LogShitou("IFSExampleActivity--updateWxpayfacePayResult", "" + GsonUtils.parseObject(info));
                                    }
                                });
                            }
                        }).start();
//                        if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_SUCCESS)) {
//                            if (TextUtils.equals(httpResult.getResult_code(), "SUCCESS")) {
//                                if (onResultListener != null) {
//                                    onResultListener.success();
//                                }
//                            } else {
//                                if (onResultListener != null) {
//                                    onResultListener.query();
//                                }
//                            }
//                            new Thread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    try {
//                                        Thread.sleep(2000);
//                                    } catch (Exception e) {
//                                    }
//                                    WxPayFace.getInstance().updateWxpayfacePayResult(new HashMap(), new IWxPayfaceCallback() {
//                                        @Override
//                                        public void response(Map info) throws RemoteException {
//                                            LogUtil.LogShitou("IFSExampleActivity--updateWxpayfacePayResult", "" + GsonUtils.parseObject(info));
//                                        }
//                                    });
//                                }
//                            }).start();
//                        } else if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_USER_CANCEL)) {
//                            if (onResultListener != null) {
//                                onResultListener.cancle();
//                            }
//                        } else if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_SCAN_PAYMENT)) {
//                            if (onResultListener != null) {
//                                onResultListener.scanPay();
//                            }
//                        } else if (TextUtils.equals(code, WxfacePayCommonCode.VAL_RSP_PARAMS_ERROR)) {
//                            if (onResultListener != null) {
//                                onResultListener.error(httpResult.getReturn_msg());
//                            }
//                        }
                    }

                    @Override
                    public void fail(String msg) {
                        onResultListener.error(msg);
                    }
                });

            }
        });
        return true;
    }

    /**
     * 扫码支付
     */
    public void scanCode(){
        WxPayFace.getInstance().startCodeScanner(new IWxPayfaceCallback() {
            @Override
            public void response(Map info) throws RemoteException {
                if (info != null){
                    String return_code = (String) info.get("return_code");
                    String return_msg = (String) info.get("return_msg");
                    String code_msg = (String) info.get("code_msg");
                    final String resultString = "startCodeScanner, return_code : " + return_code + " return_msg : " + return_msg + " code_msg: " + code_msg;
                    /**
                     这里添加业务自定义的工作即可 注意该回调在异步线程
                     **/
                    LogUtil.LogShitou("FacePayCtr--response", ""+resultString);
                }
            }
        });
    }
}